<?php
/**
 * Created by PhpStorm.
 * User: zhengze
 * Date: 2019/7/1
 * Time: 18:29
 */

namespace app\common\traits;

use Helper\StringHelper;
use app\common\token\Token;
use think\exception\DbException;

/**
 * Trait ModelTrait
 * @package common\traits
 */
trait ModelTrait
{
    protected $baseField;

    public function initBaseField()
    {
        $this->baseField = ['*', $this->getPk() => 'id'];
    }

    /**
     * 获取插入前数据前模板
     * @param array $data
     * @throws \app\common\exception\TokenException
     */
    public static function beforeInsertData($data = [])
    {
        $user_info = Token::instance()->getUserInfo();
        if ($user_info) {
            $data['creater_id'] = $user_info[$user_info->getPk()];
            $data['updater_id'] = $user_info[$user_info->getPk()];
            $data['create_time'] = $_SERVER['REQUEST_TIME'];
            $data['update_time'] = $_SERVER['REQUEST_TIME'];
        }
        return $data;
    }

    /**
     * 插入前时间
     * @param $data
     * @return bool
     * @throws \app\common\exception\TokenException
     */
    public static function onBeforeInsert($data)
    {
        $data = static::beforeInsertData($data);
        $data['status'] = 1;
        return true;
    }

    /**
     * 获取修改前数据前模板
     * @param $data
     * @return mixed
     * @throws \app\common\exception\TokenException
     */
    public static function beforeUpdateData($data)
    {
        $user_info = Token::instance()->getUserInfo();
        if ($user_info) {
            $data['updater_id'] = $user_info[$user_info->getPk()];
            $data['update_time'] = $_SERVER['REQUEST_TIME'];
        }
        return $data;
    }

    /**
     * 更新前事件
     * @param $data
     * @return bool
     * @throws \app\common\exception\TokenException
     */
    public static function onBeforeUpdate($data)
    {
        $data = static::beforeUpdateData($data);
        return true;
    }

    /**
     * 获取模型数据库名(不含前缀)
     * @return string
     */
    public function getPureName()
    {
        return StringHelper::uncamelize(lcfirst($this->getName()));
    }


}
